/**
 * 
 */
package com.jiang.factory;

/**
 * @author Administrator
 * @为了解决父Servlet自动装配Bean的单例多线程的线程安全问题，这里使用ThreadLocal
 */
@SuppressWarnings("unchecked")
public class CreateAutoBeanFactory {
	
	private  CreateAutoBeanFactory() {
	}
	
	@SuppressWarnings("rawtypes")
	private static ThreadLocal local = new ThreadLocal();
	
	public static<T> T getBean(Class<T> cls){
		
		T result = (T) local.get();
		if(result == null){
			 try {
				result = cls.newInstance();
				local.set(result);
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * 用完了记得清除
	 */
	public static<T> void clear(){
		T result = (T) local.get();
		if(result!=null){
			local.remove();
		}
	}
	
}
